import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

import Axios from "axios";

Vue.config.productionTip = false;

// 原型挂在axios

Vue.prototype.$http = Axios;
// 设置默认url
Axios.defaults.baseURL = "http://localhost:3000/";

//请求拦截

// http request 请求拦截器
Axios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    let pathname = location.pathname;
    if (localStorage.getItem("token")) {
      if (pathname != "/" && pathname != "/login") {
        config.headers.common["token"] = localStorage.getItem("token");
      }
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器

Axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        // 返回401，清除token信息并跳转到登录页面
        case 404:
          router.replace({
            path: "/about",
          });
      }
      // 返回接口返回的错误信息
      return Promise.reject(error.response.data);
    }
  }
);

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");
